#include "net.h"
#include <poll.h>

#define MAX_SOCK_FD 1024

int main(int argc, char *argv[])
{
	int fd, newfd, i, j;
	struct pollfd fds[MAX_SOCK_FD] = {};
	Addr_in addr;
	socklen_t addrlen = sizeof(Addr_in);
	nfds_t nfds = 1;

	/*检查参数，小于3个 直接退出进程*/
	Argment(argc, argv);
	/*创建已设置监听模式的套接字*/
	fd = CreateSocket(argv);
	fds[0].fd = fd;
	fds[0].events = POLLIN;
	while(1){
		if( ( poll(fds, nfds, -1) ) < 0)
			ErrExit("poll");
		for(i = 0; i < nfds; i++ ){
			/*接收客户端连接，并生成新的文件描述符*/
			if(fds[i].fd == fd && fds[i].revents & POLLIN){
				
				if( (newfd = accept(fd, (Addr *)&addr, &addrlen)) < 0)
					perror("accept");
				
				fds[nfds].fd = newfd;
				fds[nfds++].events = POLLIN;

				printf("[%s:%d][nfds=%lu]connection successful\n",
						inet_ntoa(addr.sin_addr), 
						ntohs(addr.sin_port), nfds);
				
				/*处理客户端数据*/
			}else if(fds[i].revents & POLLIN){
				if( DataHandle(fds[i].fd) <= 0){
					if( getpeername(fds[i].fd, (Addr *)&addr, &addrlen) < 0)
						ErrExit("getpeername");
					printf("[%s:%d][fd=%d] exited\n",
							inet_ntoa(addr.sin_addr), 
							ntohs(addr.sin_port), fds[i].fd);
					close(fds[i].fd);
					for(j = i; j < nfds; j++)
						fds[j] = fds[j + 1];
					nfds--;
					i--;
				}
			}
		}	
	}
	close(fd);
	return 0;
}

